<template>
  <div class="components-container">
    <el-row>
      <el-col class="name_s">
        <el-form :inline="true" :model="searchData">
          <el-form-item>
            <el-input v-model="searchData.username" size="medium" placeholder="用户名" />
          </el-form-item>

          <el-form-item>
            <el-select v-model="searchData.admin" size="medium" filterable placeholder="筛选管理员">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="warning" size="medium" icon="el-icon-search" @click="handerSearch">搜索
            </el-button>
            <el-button class="reset" type="info" size="medium" icon="el-icon-refresh-left" native-type="reset" @click="handerReset">重置
            </el-button>
            <el-button type="primary" size="medium" icon="el-icon-plus" @click="handlerCreate">新增用户
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-card class="table_style">
      <el-table v-loading="listLoading" :data="users" element-loading-text="Loading" style="width: 100%" border :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}">
        <el-table-column label="ID" prop="id" width="50px" />
        <el-table-column label="用户名">
          <template slot-scope="scope">
            <span>{{ scope.row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column label="头像">
          <template slot-scope="scope">
            <pan-thumb :image="scope.row.avatar" />
          </template>
        </el-table-column>
        <el-table-column label="是否是管理员">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.admin" @change="toggleRole(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="所属用户组">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.roleId">{{ scope.row.role.name }}</el-tag>
            <el-tag v-else type="danger">普通用户</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="加入日期">
          <template slot-scope="scope">
            <span>{{ scope.row.createdAt|time_format }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="210px">
          <template slot-scope="scope">
            <el-tooltip v-show="!scope.row.roleId" class="item" effect="dark" content="查看订单" placement="top" enterable>
              <el-button
                size="mini"
                type="success"
                icon="el-icon-view"
                @click="handleShow(scope.row)"
              />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="编辑用户" placement="top" enterable>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="handleEdit(scope.row)"
              />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除用户" placement="top" enterable>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                :disabled="scope.row.id === 1"
                @click="handleDelete(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="footer_page"
        background
        layout="total, prev, pager, next, jumper"
        :total="page.total"
        :page-size="page.pageSize"
        hide-on-single-page
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog
      title="订单列表"
      :visible.sync="showOrderDialog"
      width="100%"
      style="margin-left: 220px;margin-right: 10px;"
      :before-close="handleClose"
    >
      <el-card>
        <el-table
          ref="multipleTable"
          :data="orders"
          style="width: 100%"
          border
          :header-cell-style="{'text-align':'center'}"
          :cell-style="{'text-align':'center'}"
          center
          max-height="400"
        >
          <el-table-column type="expand" fixed>
            <template slot-scope="props">
              <el-form v-for="(product, p) in props.row.products" :key="product.id" :class="['bdbottom', p === 0 ? 'bdtop':'']" label-position="left" class="demo-table-expand" style="display: flex;padding-top: 10px;">
                <el-form-item :label="'（ '+ (p + 1) +' ）' +' 商品名称：'">
                  <span>{{ product.name }}</span>
                </el-form-item>
                <el-form-item label="商品缩略图：">
                  <span>
                    <img :src="product.image" :alt="product.name" style="width: 50px;height: 40px;">
                  </span>
                </el-form-item>
                <el-form-item label="商品单价：">
                  <span>{{ product.price }} 元</span>
                </el-form-item>
                <el-form-item label="购买数量：">
                  <span>{{ product.num }}</span>
                </el-form-item>
              </el-form>
              <span class="userAddress">收货地址：<p style="color: #42b983">{{ props.row.address.province }} {{ props.row.address.city }} {{ props.row.address.area }} {{ props.row.address.detail }}</p></span>
            </template>
          </el-table-column>
          <el-table-column label="订单号" width="400">
            <template slot-scope="scope">
              <span>{{ scope.row.outTradeNo }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用户名">
            <template slot-scope="scope">
              <span>{{ scope.row.address.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="联系方式">
            <template slot-scope="scope">
              <span>{{ scope.row.address.tel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" type="primary">{{ scope.row.status|state }}</el-tag>
              <el-tag v-else-if="scope.row.status === 2" type="success">{{ scope.row.status|state }}</el-tag>
              <el-tag v-else-if="scope.row.status === 3" type="warning">{{ scope.row.status|state }}</el-tag>
              <el-tag v-else-if="scope.row.status === 4" type="danger">{{ scope.row.status|state }}</el-tag>
              <el-tag v-else type="info">{{ scope.row.status|state }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="订单金额">
            <template slot-scope="scope">
              <el-tag type="danger">{{ scope.row.totalPrice }} 元</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="下单时间">
            <template slot-scope="scope">
              <span>{{ scope.row.createdAt|order_format }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import '../../filter'
import { fetchUserList, toggleAdmin, deleteUser, showUserOrders } from '@/api/user'
import PanThumb from '@/components/PanThumb'

export default {
  components: { PanThumb },
  filters: {
    state: (value) => {
      const arr = ['待付款', '配货中', '待发货', '待收货', '交易成功']
      return arr[value - 1]
    }
  },
  data() {
    return {
      users: [],
      orders: [],
      products: [],
      listLoading: true,
      showOrderDialog: false,
      options: [{
        value: true,
        label: '管理员'
      }, {
        value: false,
        label: '普通用户'
      }],
      searchData: {
        username: '',
        admin: ''
      },
      page: {
        total: 0,
        current_page: 1, // 当前页数
        pageSize: 0 // 每页显示多少条数据
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      // promise 写法
      this.listLoading = true
      fetchUserList(this.searchData).then(res => {
        // console.log(res)
        this.users = res.data.users
        this.page = {
          total: res.data.pagination.total,
          pageSize: parseInt(res.data.pagination.pageSize),
          current_page: parseInt(res.data.pagination.current_page)
        }
        this.listLoading = false
      })
    },
    handerSearch() {
      this.init()
    },
    handleCurrentChange(val) {
      this.page.current_page = val
      this.init()
    },
    // 搜索后重置搜索内容
    handerReset() {
      this.searchData = {
        username: '',
        admin: ''
      }
      this.init()
    },
    // 切换管理员
    toggleRole(row) {
      // promise 写法
      toggleAdmin(row.id).then(res => {
        if (res.code === 20000) return this.$message.success(res.message)
        this.init()
        return this.$message.error(res.message)
      })
    },
    // 新增用户
    handlerCreate() {
      this.$router.push({ name: 'UserCreate' })
    },
    // 加载编辑用户页面
    handleEdit(row) {
      this.$router.push({
        name: 'UserEdit',
        params: { id: row.id }
      })
    },
    // 关闭弹出框
    handleClose(done) {
      done()
    },
    // 查看订单
    async handleShow(row) {
      this.showOrderDialog = true
      const res = await showUserOrders(row.id)
      console.log(res)
      this.orders = res.data.orders
    },
    // 删除用户
    handleDelete(row) {
      this.$confirm('确定要删除该用户吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        // promise 写法
        deleteUser(row.id).then(res => {
          this.init()
          this.$message({
            type: 'success',
            message: res.message
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped>
.name_s {
  margin: 15px 0 0 15px;
}
.table_style {
  margin: 0 15px;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.userAddress{
  display:flex;
  align-items:center;
  color: #333333;
  font-size: 14px;
  font-weight: 700;
  line-height: 40px;
}
.bdtop{
  border-top: 1px solid #eee;
}

.bdbottom{
  border-bottom: 1px solid #eee;
}
</style>
